package com.ehotting.mqbd.core.manager;

import com.ehotting.eaf.redis.service.RedisService;
import com.ehotting.mqbd.api.MQDBConstants;
import com.ehotting.mqbd.api.bean.solver.SolverCountBean;
import com.ehotting.mqbd.api.bean.solver.SolverStateBean;
import com.ehotting.mqbd.api.enums.ServerAvailableStateEnum;
import com.ehotting.mqbd.api.enums.ServerWorkStateEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class SolverCountManager {

    private RedisService redisService;

    private SolverInfoManager solverInfoManager;

    public SolverCountManager(RedisService redisService, SolverInfoManager solverInfoManager) {
        this.redisService = redisService;
        this.solverInfoManager = solverInfoManager;
    }

    public List<SolverCountBean> countByState(){
        List<SolverCountBean> list = new ArrayList<>();
        Map<String, List<SolverStateBean>> solverStateMap = solverInfoManager.getMapServerInfoList();
        if(solverStateMap==null){
            return list;
        }

        Set<Map.Entry<String, List<SolverStateBean>>> solverStateSet = solverStateMap.entrySet();

        for(Map.Entry<String,List<SolverStateBean>> entry :  solverStateSet){
            SolverCountBean solverCountBean = new SolverCountBean();
            solverCountBean.setModule(entry.getKey());
            solverCountBean.setAllCount((long)entry.getValue().size());
            solverCountBean.setBusyCount(entry.getValue()==null?0:entry.getValue().stream().filter(t->t.getWorkingState()== ServerWorkStateEnum.BUSY).count());
            solverCountBean.setFreeCount(entry.getValue()==null?0:entry.getValue().stream().filter(t->(t.getWorkingState()!=ServerWorkStateEnum.BUSY
                    && t.getAvailableState()== ServerAvailableStateEnum.YES )).count());
            solverCountBean.getServerList().addAll(entry.getValue());
            list.add(solverCountBean);
        }
        list = list.stream().sorted(Comparator.comparing(t->t.getModule())).collect(Collectors.toList());
        return list;
    }

    public void saveCount(List<SolverCountBean> list){
        log.info("list.size():{}",list.size());
        redisService.setCacheList(MQDBConstants.SERVER_COUNT,list);
    }

    public List<SolverCountBean> getCountAll(){
        return redisService.getCacheList(MQDBConstants.SERVER_COUNT);
    }


}
